<template>
  <div class="appointmentList-container">
    <!-- <div class="header">
      <el-header>
        <div class="header-left">
          <div class="header-left-name">患者预约信息列表</div>
        </div>
      </el-header>
    </div> -->
    <el-tabs type="border-card"
             @tab-click="changeTab">
      <el-tab-pane v-for="tab in tabs"
                   :key="tab"
                   :label="tab">
        <div class="appointmentList-container-table">
          <el-table :data="tableData"
                    style="width: 100%"
                    :row-class-name="tableRowClassName">
            <el-table-column prop="time"
                             label="预约时间"
                             :formatter="formatterTime"
                             align="center"
                             width="180">
            </el-table-column>
            <el-table-column prop="id"
                             label="订单号"
                             align="center"
                             width="180">
            </el-table-column>
            <el-table-column prop="patient.name"
                             label="姓名"
                             align="center"
                             width="180">
            </el-table-column>
            <el-table-column prop="patient.idNumber"
                             label="身份证号"
                             align="center"
                             width="200">
            </el-table-column>
            <el-table-column prop="patient.sex"
                             label="性别"
                             align="center"
                             width="180">
            </el-table-column>
            <el-table-column label="操作"
                             width="300"
                             v-if="tab != '已取消'"
                             align="center">

              <template slot-scope="scope">
                <el-button size="mini"
                           @click="recommendMedicine(scope.$index, scope.row)">推荐药品</el-button>
                <!--原本是编辑 -->
                <el-button size="mini"
                           @click="viewHaveRecommendMedicine(scope.$index, scope.row)"
                           type="primary">查看推荐药品</el-button>
                <!--原本是编辑 -->
                <el-button size="mini"
                           type="danger"
                           v-if="tab != '已完成'"
                           @click="handleEndTheOrder(scope.$index, scope.row)">结束</el-button>
                <!--原本是删除 -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

    </el-tabs>
    <el-dialog title="药品列表"
               :visible.sync="recommendDialogVisible">
      <div class="medicine-list-container">
        <el-input v-if="!isViewRecommendMedicine" placeholder="请输入内容"
                  v-model="searchMedicine"
                  class="medicine-list-input"
                  clearable>
          <el-button slot="append"
                     icon="el-icon-search"
                     @click="searchMedicineListData"></el-button>
        </el-input>
        <el-button class="batch-delete" v-if="isViewRecommendMedicine" type="danger"
                   @click="batchDelete">批量删除</el-button>
        <el-button v-if="!isViewRecommendMedicine" type="primary"
                   @click="handleRecommendMedicine">立即推荐</el-button>
      </div>
      <el-table :data="medicineList"
                @selection-change="handleSelectedMedicineChange">
        <el-table-column type="selection"
                         width="55" >
        </el-table-column>
        <el-table-column property="image"
                         label="图片"
                         width="150">
          <template slot-scope="scope">
            <img class="medicine-list-image"
                 :src="scope.row.image"
                 alt="药品图片"
                 srcset="">
          </template>
        </el-table-column>
        <!-- </el-table-column> -->
        <el-table-column property="name"
                         label="姓名"
                         width="200"></el-table-column>
        <el-table-column property="description"
                         width="500"
                         label="描述"></el-table-column>
        <el-table-column label="操作"
                         width="100"
                         v-if="isViewRecommendMedicine"
                         
                         align="center">
                         <!-- v-if="tab != '已取消'" -->
          <template slot-scope="scope">
            <el-button size="mini"
                       type="danger"
                       @click="deleteMedicine(scope.$index, scope.row)">删除</el-button>
            <!--原本是删除 -->
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderByStatus, doctorGetMedicineList, doctorRecommendMedicine, searchMedicines,cancelRecommendMedicine } from "@/api/doctor.js"
import { cancelOrder, getMedicineList } from "@/api/user.js";
import { parseTime } from "@/utils/index"
import { mapGetters } from 'vuex'
export default {
  name: 'AppointmentList',
  data () {
    return {
      tableData: [],
      search: '',
      tabs: ['未完成', '已取消', '已完成'],
      medicineList: [],
      recommendDialogVisible: false,
      searchMedicine: "",
      selectedRow: "",
      selectedMedicine: [],
      isViewRecommendMedicine: false
    }
  },
  created () {
    this.getUserByStatus(0)
  },
  computed: {
    ...mapGetters(["user"]),
  },
  methods: {
    async getUserByStatus (status) {
      const id = localStorage.getItem('token')
      const { data } = await getOrderByStatus({ id, status })
      this.tableData = data || []
      console.log(data)
    },
    async recommendMedicine (index, row) {
      const { data } = await doctorGetMedicineList()
      this.selectedRow = row
      console.log(data);
      this.medicineList = data || []
      this.recommendDialogVisible = true
      this.isViewRecommendMedicine = false
    },
    handleEndTheOrder (index, row) {
      console.log(index, row);
      this.$confirm("此操作将结束该预约, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let { code } = await cancelOrder({ id: row.id, status: 2 });
          console.log(code);
          this.getUserByStatus(0)
          if (code == 200) {
            this.$message({
              type: "success",
              message: "订单已结束!",
            });

          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'warning-row';
      } else if (rowIndex) {
        return 'success-row';
      }
      return '';
    },
    changeTab (tab) {
      console.log(tab.index)
      this.getUserByStatus(tab.index)
    },
    formatterTime (row) {
      return parseTime(row.time)
    },
    async searchMedicineListData () {
      console.log('search', this.searchMedicine)
      const {data} = await searchMedicines({name:this.searchMedicine})
      this.medicineList = data || []
    },
    handleRecommendMedicine () {
      if (this.selectedMedicine.length < 1) {
        this.$message.error('请先选择药品')
        return
      }
      let haveUnfinished = false
      this.selectedMedicine.forEach(async (medicine) => {
        console.log(medicine, this.selectedRow)
        const { id } = this.selectedRow
        const { patientId } = this.selectedRow.patient
        const res = await doctorRecommendMedicine({ patientId, doctorId:this.user.id, appointmentId: id, medicineId: medicine.id })
        console.log(res)
        if (res.code != 200) {
          haveUnfinished = true
          this.$message.error(medicine.name + '未推荐成功，请稍后重新推荐')
        }
      })
      if (!haveUnfinished) {
        this.$message.success('推荐成功')
        this.recommendDialogVisible = false
      }
    },
    handleSelectedMedicineChange (list) {
      this.selectedMedicine = list
    },
    async viewHaveRecommendMedicine (index, row) {
      this.selectedRow = row
      console.log(index, row)
      let { data } = await getMedicineList(row.id)
      if (data) {
        this.medicineList = data
      }
      this.recommendDialogVisible = true
      this.isViewRecommendMedicine = true
    },
    async deleteMedicine (index, row) {
      console.log(index, row, this.selectedRow)
      const res = await cancelRecommendMedicine({medicineId:row.id,appointmentId:this.selectedRow.id})
      if(res.code == 200){
        this.$message.success('删除成功')
        this.viewHaveRecommendMedicine(index,this.selectedRow)
      }
    },
    batchDelete(){
         if (this.selectedMedicine.length < 1) {
        this.$message.error('请先选择药品')
        return
      }
      let haveUnfinished = false
      this.selectedMedicine.forEach(async (medicine) => {
        console.log(medicine, this.selectedRow)
        const { id } = this.selectedRow
        const res = await cancelRecommendMedicine({appointmentId: id, medicineId: medicine.id })
        console.log(res)
        if (res.code != 200) {
          haveUnfinished = true
          this.$message.error(medicine.name + '未删除成功，请稍后重新删除')
        }
      })
      if (!haveUnfinished) {
        this.$message.success('删除成功')
        this.recommendDialogVisible = false
      }
    }
  },
}
</script>

<style lang='scss'>
.appointmentList-container {
  .text-primary {
    color: var(--primary) !important;
  }
  .el-table .warning-row {
    background: #f0f9eb;
  }

  .el-table .success-row {
    background: oldlace;
  }

  .el-tabs--border-card {
    margin: 2rem;
  }

  .medicine-list-image {
    width: 100px;
  }

  .medicine-list-input {
    width: 14rem;
  }

  .medicine-list-container {
    display: flex;
    justify-content: space-between;
  }
}


.batch-delete{
  margin-left: auto;
}
.navbar-light .navbar-nav .nav-link {
  // font-family: 'Jost', sans-serif;
  font-family: "SimHei", sans-serif;
  position: relative;
  margin-left: 1.875rem; //导航栏间隔
  padding: 1.875rem 0;
  // font-size: 0.625rem;
  font-size: 1.125rem;
  font-weight: 700;
  color: var(--dark);
  outline: none;
  transition: 0.5s;
}

.navbar-light .navbar-nav .nav-link:hover,
.navbar-light .navbar-nav .nav-link.active {
  color: var(--primary);
}

@media (min-width: 62rem) {
  .navbar-light .navbar-nav .nav-link::before {
    position: absolute;
    content: "";
    width: 0;
    height: 0.3125rem;
    bottom: 0;
    left: 50%;
    background: var(--primary);
    transition: 0.5s;
  }

  .navbar-light .navbar-nav .nav-link:hover::before,
  .navbar-light .navbar-nav .nav-link.active::before {
    width: 100%;
    left: 0;
  }
}

@media (max-width: 61.99875rem) {
  .navbar-light .navbar-nav .nav-link {
    margin-left: 0;
    padding: 0.625rem 0;
  }
}
</style>

<!-- <style lang="scss">
// .appointmentList-container{
//   .header {
//     height: 3rem;

//     display: flex;
//     align-items: center;
//     width: 100%;
//     font-size: 1.5rem;
//     .el-header {
//       background-color: white;
//       width: 100%;
//       border-bottom: 1px solid #cccccc;
//       display: flex;
//       align-items: center;
//       position: fixed;
//       height: 3rem;
//       font-size: 1.5rem;
//       z-index: 9;
//     }
//   }
//   &-table{
//     margin-top: 3rem;
//   }
// }
// </style>